const db = require('../db');

class UserModel {
    // 创建用户
    static async create(userData) {
        try {
            const [result] = await db.query('INSERT INTO users SET ?', userData);
            return result;
        } catch (error) {
            throw error;
        }
    }

    // 根据ID查询用户
    static async findById(id) {
        try {
            const [rows] = await db.query('SELECT * FROM users WHERE id = ?', [id]);
            return rows[0] || null;
        } catch (error) {
            throw error;
        }
    }

    // 查询所有用户
    static async findAll() {
        try {
            const [rows] = await db.query('SELECT * FROM users');
            return rows;
        } catch (error) {
            throw error;
        }
    }

    // 更新用户信息
    static async update(id, userData) {
        try {
            const [result] = await db.query('UPDATE users SET ? WHERE id = ?', [userData, id]);
            return result;
        } catch (error) {
            throw error;
        }
    }

    // 删除用户
    static async delete(id) {
        try {
            const [result] = await db.query('DELETE FROM users WHERE id = ?', [id]);
            return result;
        } catch (error) {
            throw error;
        }
    }

    // 检查邮箱是否已存在
    static async checkEmailExists(email) {
        try {
            const [rows] = await db.query('SELECT COUNT(*) as count FROM users WHERE email = ?', [email]);
            return rows[0].count > 0;
        } catch (error) {
            throw error;
        }
    }

    // 创建新用户（注册）
    static async register(userData) {
        try {
            const [result] = await db.query('INSERT INTO users SET ?', userData);
            return result;
        } catch (error) {
            throw error;
        }
    }

    // 通过邮箱查找用户（用于登录）
    static async findByEmailWithPassword(email) {
        try {
            const [rows] = await db.query('SELECT * FROM users WHERE email = ?', [email]);
            return rows[0] || null;
        } catch (error) {
            throw error;
        }
    }

    // 重置密码
    static async resetPassword(email, newPassword) {
        try {
            const [result] = await db.query('UPDATE users SET password = ? WHERE email = ?', [newPassword, email]);
            return result;
        } catch (error) {
            throw error;
        }
    }

    // 更新用户信息（根据ID）
    static async updateUserInfo(id, userData) {
        try {
            const [result] = await db.query('UPDATE users SET ? WHERE id = ?', [userData, id]);
            return result;
        } catch (error) {
            throw error;
        }
    }

    // 根据用户名查找用户
    static async findByName(name) {
        try {
            const [rows] = await db.query('SELECT * FROM users WHERE name = ?', [name]);
            return rows[0] || null;
        } catch (error) {
            throw error;
        }
    }

    // 获取用户关系
    static async getUserRelationships(userId) {
        try {
            const [rows] = await db.query(`
                SELECT ur.*, u.name as friend_name, u.avatar as friend_avatar, u.email as friend_email 
                FROM user_relationships ur
                JOIN users u ON ur.friend_id = u.id
                WHERE ur.user_id = ?
            `, [userId]);
            return rows;
        } catch (error) {
            throw error;
        }
    }

    // 获取向指定用户发送好友申请的用户列表
    static async getFriendRequests(userId) {
        try {
            const [rows] = await db.query(`
                SELECT ur.*, u.name as requester_name, u.avatar as requester_avatar, u.email as requester_email 
                FROM user_relationships ur
                JOIN users u ON ur.user_id = u.id
                WHERE ur.friend_id = ?
            `, [userId]);
            return rows;
        } catch (error) {
            throw error;
        }
    }

    // 更新用户关系
    static async updateRelationship(userId, friendId, relationshipData) {
        try {
            // 确保relationshipData是字符串
            if (typeof relationshipData !== 'string') {
                throw new Error('关系数据必须是字符串类型');
            }

            const [result] = await db.query(
                'UPDATE user_relationships SET relationship = ? WHERE user_id = ? AND friend_id = ?',
                [relationshipData, userId, friendId]
            );
            return result;
        } catch (error) {
            throw error;
        }
    }

    // 创建用户关系
    static async createRelationship(userId, friendId, relationshipData) {
        try {
            // 确保relationshipData是字符串
            if (typeof relationshipData !== 'string') {
                throw new Error('关系数据必须是字符串类型');
            }

            // 检查关系是否已存在
            const [existing] = await db.query(
                'SELECT * FROM user_relationships WHERE user_id = ? AND friend_id = ?',
                [userId, friendId]
            );

            if (existing.length > 0) {
                throw new Error('关系已存在');
            }

            // 创建新关系
            const [result] = await db.query(
                'INSERT INTO user_relationships (user_id, friend_id, relationship) VALUES (?, ?, ?)',
                [userId, friendId, relationshipData]
            );
            return result;
        } catch (error) {
            throw error;
        }
    }

    // 分页获取用户列表
    static async getUsersWithPagination(limit = 10, offset = 0) {
        try {
            const [rows] = await db.query(
                'SELECT id, email, name, avatar FROM users LIMIT ? OFFSET ?',
                [parseInt(limit), parseInt(offset)]
            );
            return rows;
        } catch (error) {
            throw error;
        }
    }

    // 根据关键词搜索用户
    static async searchUsers(keywords, limit = 10, offset = 0) {
        try {
            const searchPattern = `%${keywords}%`;
            const [rows] = await db.query(
                'SELECT id, email, name, avatar FROM users WHERE name LIKE ? OR email LIKE ? LIMIT ? OFFSET ?',
                [searchPattern, searchPattern, parseInt(limit), parseInt(offset)]
            );
            return rows;
        } catch (error) {
            throw error;
        }
    }
}

module.exports = UserModel; 